import cgi
from google.appengine.ext.webapp.util import run_wsgi_app
from forms import *
from vote_handler import VotePage
from creation_handler import PollCreationPage

class PollMainPage(webapp.RequestHandler):
  def get(self):
    if users.get_current_user():
      if self.request.get("user") == "true":
        polls_query = Poll.all().order('start_date').filter("owner = ", users.get_current_user())
      else:
        polls_query = Poll.all().order('start_date')
      polls = polls_query.fetch(5)
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      polls = None
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'
      self.redirect(url)

    template_values = {
      'polls': polls,
      'url': url,
      'url_linktext': url_linktext,
      }
    path = os.path.join(os.path.dirname(__file__), 'list.html')
    self.response.out.write(template.render(path, template_values))


application = webapp.WSGIApplication([('/', PollMainPage),
                                      ('/create', PollCreationPage),
                                      ('/vote', VotePage)],
                                     debug=True)

def main():
  logging.getLogger().setLevel(logging.DEBUG)
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
